/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2021-11-20 17:28:15
 * 天凉好个秋
 */

import { Rules } from "async-validator/dist-types/interface";
import { Context } from "koa";
import { sign } from "../../utils/auth";
import response from "../../utils/response";
import { encryptPassword } from "../../utils/util";
import vaildate from "../../utils/validate";
import UserService from "../service/UserService";

class LoginController {
  async index(ctx: Context) {
    interface IUser {
      name: string;
      password: string;
    }

    const rules: Rules = {
      name: [{ type: "string", required: true, message: "用户名不能为空" }],
      password: [
        { type: "string", required: true, message: "密码不能为空" },
        { min: 6, max: 15, message: "密码长度应在6-15位之间" },
      ],
    };
    const { data, error } = await vaildate<IUser>(ctx, rules);
    if (!error) {
      try {
        const { name, password } = data;
        const User = await UserService.getUserByName(name);
        if (User === null) return response.error(ctx, `用户 '${name}' 不存在`);
        if (encryptPassword(password) === User['dataValues'].password) {
          const token = sign(User);
          User["dataValues"].token = token;
          response.success(ctx, User);
        } else {
          response.error(ctx, "密码不正确");
        }
      } catch (err) {
        response.error(ctx, err);
      }
    } else {
      response.error(ctx, error);
    }
  }
}

export default new LoginController();
